import json


def validate_json(data):
    # 检查数据是否为列表
    if not isinstance(data, list):
        return False, "Data is not a valid JSON array"

    # 遍历列表中的每个字典对象
    for index, item in enumerate(data):
        # 检查每个元素是否为字典
        if not isinstance(item, dict):
            return False, f"Item at index {index} is not a valid JSON object"

        # 检查必需字段
        for field in ['english', 'chinese']:
            if field not in item:
                return False, f"Missing required field '{field}' in item at index {index}"

            value = item[field]

            # 检查字段值是否为空或不符合格式
            if value is None:
                return False, f"Field '{field}' is None in item at index {index}"
            if isinstance(value, str) and value.strip() == "":
                return False, f"Field '{field}' is an empty string in item at index {index}"

    return True, "Valid JSON data"


# 从 .json 文件中读取数据
def load_json_from_file(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
        return data  # 只返回数据
    except Exception as e:
        return None, str(e)


# 文件路径
file_path = r'D:\FengGong_Project\Machine Translation(transformer)\data\PaddlePaddle\train_2k.json'  # 请替换为您的 .json 文件路径

# 加载 JSON 数据
data = load_json_from_file(file_path)

if data is None:
    print(f"Error loading JSON data: {data}")
else:
    # 验证数据
    is_valid, message = validate_json(data)
    print(is_valid, message)
